<?php
/**
 * 前端缓存
 * @author GhostWei
 * @date Sep 5, 2012
 */
class system_view_cache extends system_cache_file {

	public $file = null;
	protected $lang = 'en_us';
	protected $base_dir = _DIRECTORY_VAR;
	protected $_data = array();
	
	public function __construct() {
		$expire = system_session::getOptions('cache_expire');
		$this->lang = system_nav_language::getInstance()->getName();
		$this->base_dir = _DIRECTORY_VAR . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . $this->lang;
		$this->_options['expire'] = rand($expire * 0.1, $expire * 1.1);
		$this->_options['dir'] = $this->base_dir;
		$this->_options['suffix'] = '';
		$this->init();
		parent::__construct($this->_options);
	}
	
	public function init(){}
	
	public function __call($method, array $args) {
		if(preg_match('/^get(\w+?)$/', $method, $matches)) {
			$_id = strtolower(trim(preg_replace('/([A-Z]{1})/sU', '-$1', $matches[1]), '-'));

			$this->file = $this->md5Path(md5($_id . serialize($args)));
			$fp = pathinfo($this->file);
			$index = $fp['filename'];
			if(isset($this->_data[$index])) {
				return $this->_data[$index];
			}
			$this->_options['dir'] = $this->base_dir . dirname($this->file);
			$this->setOptions($this->_options);
			if(!($data = $this->load($index))) {
				$func = create_function('$m', 'return strtolower("_" . $m[1]);');
				$_method = preg_replace_callback('/([A-Z]+)/', $func, $matches[1]);
				$_method = trim($_method, '_');
				$data = $this->$_method(isset($args[0]) ? $args[0] : array());
				$this->save($index, $data);
			}
			$this->_data[$index] = $data;
			return $data;
		}
		return null;
	}
	
	protected function url($index, $params = array(), $query = array()) {
		return (string) $this->getView()->url($index, $params, $query);
	}
	
	protected function image($hash, $secure = false) {
		$img = new resource_display($hash);
		$result = array();
		foreach(array('small', 'thumb', 'middle', 'large', 'original') AS $v) {
			$result[$v] = $img->get($v, $secure);
		}
		return $result;
	}
	
	private function md5Path($code) {
		$a = substr($code, 1, 1);
		$b = substr($code, -2, 2);
		$c = substr($code, 8, 16);
		return "/$a/$b/$c";
	}


	protected $view = null;
	/**
	 * @return system_view_abstract
	 */
	public function getView() {
		return $this->view;
	}
	public function setView(system_view_interface $view) {
		$this->view = $view;
		return $this;
	}
	
}
